import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Tag, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import AddDeviceAuthForm from './components/AddDeviceAuthForm';
import { DeviceAuthListItem } from './data.d';
import { deviceAuthList, addDeviceAuth, updateDeviceAuth, authDeviceDel } from './service';

const AuthList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<DeviceAuthListItem>({});
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  //添加
  const addComment = (user: DeviceAuthListItem) => {
    new Promise((resolve, reject) => {
      addDeviceAuth(user)
        .then((res) => {
          if (res.code === 200) {
            const hide = message.success('添加成功');
            handleModalVisible(false);
            if (actionRef.current) {
              hide();
              actionRef.current.reload();
            }
            resolve(true);
          } else {
            message.error('添加失败，'+res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('添加失败');
          reject(error);
        });
    });
  };

  //编辑
  const updateComment = (user: DeviceAuthListItem) => {
    new Promise((resolve, reject) => {
      updateDeviceAuth(user)
        .then((res) => {
          if (res.code === 200) {
            const hide = message.success('保存成功');
            handleModalVisible(false);
            if (actionRef.current) {
              hide();
              actionRef.current.reload();
            }
            resolve(true);
          } else {
            message.error('保存失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('保存失败');
          reject(error);
        });
    });
  };

  //【新建/编辑】对话框，确定按钮点击
  const handleUpdate = async (values: DeviceAuthListItem) => {
    if (values != null && values != undefined) {
      values.commands = values.commands.toString();
      if (values.id != undefined) {
        //编辑用户
        updateComment(values);
      } else {
        //添加用户
        addComment(values);
      }
    }
  };
  //删除--删除弹出框
  const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此记录将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          authDeviceDel(id)
            .then((res) => {
              if (res.code === 200) {
                message.success('删除成功');
                handleDeleteModalVisible(false);
                actionRef.current?.reload?.();
                resolve(true);
              } else {
                message.error('删除失败');
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };
  const columns: ProColumns<DeviceAuthListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '固件版本',
      dataIndex: 'deviceVersion',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '板卡型号',
      dataIndex: 'boardModel',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '具有功能',
      dataIndex: 'commandList',
      valueType: 'text',
      hideInSearch: true, 
      render: commandList => (
        <>
          {commandList?.map((command, index) => {
            return (
              <Tag color="blue" key={index} title={command} style={{marginBottom:5,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:130}}>
                {command}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateDatetime',
      valueType: 'dateTime',
      hideInSearch: true, 
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
             onClick={() => {
              delConfirm(record.id);
            }}
          >删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<DeviceAuthListItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={false}
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }} //默认每页显示10条
        toolBarRender={() => [
          <Button type="primary" onClick={() => {handleModalVisible(true);setFormValues({})}}>
            <PlusOutlined /> 添加设备认证
          </Button>,
        ]}
        request={(params, sorter, filter) => deviceAuthList({ ...params, sorter, filter })}
        columns={columns}
      />
      <AddDeviceAuthForm
        onSubmit={handleUpdate}
        onCancel={() => handleModalVisible(false)} 
        modalVisible={createModalVisible}
        values={formValues}
      >
        <ProTable<DeviceAuthListItem, DeviceAuthListItem>
        />
      </AddDeviceAuthForm>
    </PageContainer>
  );
};

export default AuthList;
